/**
 * CSS解析器模块
 * @version 1.0.0
 */

import { utils } from '../../utils/utils.js';
import { defaultColors } from '../../utils/colors.js';

// 解析带单位的值 - 只处理 uvue 文件
export function parseValueWithUnit(value, options = {}) {
    const { platform = 'H5', h5Unit = 'rem', remBase = 16 } = options;
    
    // 处理带单位的值 (如: 30rpx, 100px, 2rem, 50%, 100vw 等)
    const unitMatch = value.match(/^(\d+(?:\.\d+)?)(rpx|px|rem|em|vh|vw|vmin|vmax|%|pt|pc|in|mm|cm)$/);
    if (unitMatch) {
        const [, numValue, unit] = unitMatch;
        
        // uni-app x APP端只支持 number|pixel|percent|auto
        if (platform === 'APP-PLUS' || platform === 'APP-ANDROID' || platform === 'APP-IOS') {
            if (unit === 'rem') {
                return `${numValue * remBase}px`;
            } else if (unit === 'em') {
                return `${numValue * 16}px`;
            } else if (unit === 'vw') {
                return `${numValue}%`;
            } else if (unit === 'vh') {
                return `${numValue}%`;
            } else if (unit === 'vmin' || unit === 'vmax') {
                return `${numValue}%`;
            } else if (unit === '%') {
                return `${numValue}%`;
            } else if (unit === 'rpx') {
                return `${numValue}rpx`;
            } else if (unit === 'px') {
                return `${numValue}px`;
            } else {
                // 其他单位转换为px
                return `${numValue * 16}px`;
            }
        } else {
            return `${numValue}${unit}`;
        }
    }
    
    // 处理纯数字值
    if (/^\d+(?:\.\d+)?$/.test(value)) {
        return utils.convertUnit(value, platform, { h5Unit, remBase });
    }
    
    // 处理特殊值
    if (['auto', 'inherit', 'initial', 'unset'].includes(value)) {
        return value;
    }
    
    return null;
}

// 方括号语法解析器
export function parseBracketSyntax(property, value, options = {}) {
    const { platform = 'H5', h5Unit = 'rem', remBase = 16 } = options;
    
    // 颜色值解析 (支持 #333, #ff0000, rgb(255,0,0), rgba(255,0,0,0.5) 等)
    if (['text', 'bg', 'border'].includes(property)) {
        const cssProperty = {
            'text': 'color',
            'bg': 'background-color',
            'border': 'border-color'
        }[property];
        
        // 处理十六进制颜色 (#333, #ff0000, #ff000080, #f008)
        if (value.startsWith('#')) {
            const hex = value.slice(1);
            if (/^[0-9a-f]{3}$/i.test(hex)) {
                // 3位十六进制转6位
                const expandedHex = hex.split('').map(c => c + c).join('');
                return { [cssProperty]: `#${expandedHex}` };
            } else if (/^[0-9a-f]{4}$/i.test(hex)) {
                // 4位十六进制（带透明度）转8位
                const r = parseInt(hex[0] + hex[0], 16);
                const g = parseInt(hex[1] + hex[1], 16);
                const b = parseInt(hex[2] + hex[2], 16);
                const a = parseInt(hex[3] + hex[3], 16) / 255;
                return { [cssProperty]: `rgba(${r}, ${g}, ${b}, ${a.toFixed(3)})` };
            } else if (/^[0-9a-f]{6}$/i.test(hex)) {
                // 6位十六进制
                return { [cssProperty]: value };
            } else if (/^[0-9a-f]{8}$/i.test(hex)) {
                // 8位十六进制（带透明度）
                const r = parseInt(hex.slice(0, 2), 16);
                const g = parseInt(hex.slice(2, 4), 16);
                const b = parseInt(hex.slice(4, 6), 16);
                const a = parseInt(hex.slice(6, 8), 16) / 255;
                return { [cssProperty]: `rgba(${r}, ${g}, ${b}, ${a.toFixed(3)})` };
            }
        }
        
        // 处理 rgb/rgba 函数 - 确保语法正确
        if (value.startsWith('rgb(') || value.startsWith('rgba(')) {
            // 验证RGB/RGBA语法是否正确
            const rgbPattern = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(0(?:\.\d+)?|1(?:\.0+)?))?\s*\)$/;
            if (rgbPattern.test(value)) {
                return { [cssProperty]: value };
            } else {
                // 如果语法不正确，尝试修复
                const match = value.match(/rgba?\(([^)]+)\)/);
                if (match) {
                    const params = match[1].split(',').map(p => p.trim());
                    if (params.length >= 3) {
                        const r = parseInt(params[0]) || 0;
                        const g = parseInt(params[1]) || 0;
                        const b = parseInt(params[2]) || 0;
                        const a = params[3] ? parseFloat(params[3]) : 1;
                        
                        if (params.length === 4 || value.startsWith('rgba(')) {
                            return { [cssProperty]: `rgba(${r}, ${g}, ${b}, ${a})` };
                        } else {
                            return { [cssProperty]: `rgb(${r}, ${g}, ${b})` };
                        }
                    }
                }
            }
        }
        
        // 处理 hsl/hsla 函数 - 确保语法正确
        if (value.startsWith('hsl(') || value.startsWith('hsla(')) {
            // 验证HSL/HSLA语法是否正确
            const hslPattern = /^hsla?\(\s*(\d+)\s*,\s*(\d+%)\s*,\s*(\d+%)\s*(?:,\s*(0(?:\.\d+)?|1(?:\.0+)?))?\s*\)$/;
            if (hslPattern.test(value)) {
                return { [cssProperty]: value };
            } else {
                // 如果语法不正确，尝试修复
                const match = value.match(/hsla?\(([^)]+)\)/);
                if (match) {
                    const params = match[1].split(',').map(p => p.trim());
                    if (params.length >= 3) {
                        const h = parseInt(params[0]) || 0;
                        const s = params[1].includes('%') ? params[1] : `${parseInt(params[1]) || 0}%`;
                        const l = params[2].includes('%') ? params[2] : `${parseInt(params[2]) || 0}%`;
                        const a = params[3] ? parseFloat(params[3]) : 1;
                        
                        if (params.length === 4 || value.startsWith('hsla(')) {
                            return { [cssProperty]: `hsla(${h}, ${s}, ${l}, ${a})` };
                        } else {
                            return { [cssProperty]: `hsl(${h}, ${s}, ${l})` };
                        }
                    }
                }
            }
        }
        
        // 处理颜色名称
        if (defaultColors[value]) {
            const colorValue = defaultColors[value];
            return { [cssProperty]: colorValue.includes(',') ? `rgb(${colorValue})` : colorValue };
        }
    }
    
    // 尺寸值解析 (支持 30rpx, 100px, 2rem, 50%, 100vw 等)
    if (['w', 'h', 'min-w', 'max-w', 'min-h', 'max-h'].includes(property)) {
        const cssProperty = {
            'w': 'width',
            'h': 'height',
            'min-w': 'min-width',
            'max-w': 'max-width',
            'min-h': 'min-height',
            'max-h': 'max-height'
        }[property];
        
        return { [cssProperty]: parseValueWithUnit(value, { platform, h5Unit, remBase }) };
    }
    
    // 字体大小解析
    if (property === 'text') {
        // 如果不是颜色，可能是字体大小
        const parsedValue = parseValueWithUnit(value, { platform, h5Unit, remBase });
        if (parsedValue) {
            return { 'font-size': parsedValue };
        }
    }
    
    // 间距解析 (margin, padding)
    if (['m', 'p', 'mx', 'my', 'px', 'py', 'mt', 'mr', 'mb', 'ml', 'pt', 'pr', 'pb', 'pl'].includes(property)) {
        const propertyMap = {
            'm': ['margin'],
            'p': ['padding'],
            'mx': ['margin-left', 'margin-right'],
            'my': ['margin-top', 'margin-bottom'],
            'px': ['padding-left', 'padding-right'],
            'py': ['padding-top', 'padding-bottom'],
            'mt': ['margin-top'],
            'mr': ['margin-right'],
            'mb': ['margin-bottom'],
            'ml': ['margin-left'],
            'pt': ['padding-top'],
            'pr': ['padding-right'],
            'pb': ['padding-bottom'],
            'pl': ['padding-left']
        };
        
        const cssProperties = propertyMap[property];
        if (cssProperties) {
            const parsedValue = parseValueWithUnit(value, { platform, h5Unit, remBase });
            if (parsedValue) {
                const styles = {};
                cssProperties.forEach(prop => {
                    styles[prop] = parsedValue;
                });
                return styles;
            }
        }
    }
    
    // 圆角解析
    if (['rounded', 'rounded-t', 'rounded-r', 'rounded-b', 'rounded-l', 'rounded-tl', 'rounded-tr', 'rounded-br', 'rounded-bl'].includes(property)) {
        const propertyMap = {
            'rounded': ['border-radius'],
            'rounded-t': ['border-top-left-radius', 'border-top-right-radius'],
            'rounded-r': ['border-top-right-radius', 'border-bottom-right-radius'],
            'rounded-b': ['border-bottom-left-radius', 'border-bottom-right-radius'],
            'rounded-l': ['border-top-left-radius', 'border-bottom-left-radius'],
            'rounded-tl': ['border-top-left-radius'],
            'rounded-tr': ['border-top-right-radius'],
            'rounded-br': ['border-bottom-right-radius'],
            'rounded-bl': ['border-bottom-left-radius']
        };
        
        const cssProperties = propertyMap[property];
        if (cssProperties) {
            const parsedValue = parseValueWithUnit(value, { platform, h5Unit, remBase });
            if (parsedValue) {
                const styles = {};
                cssProperties.forEach(prop => {
                    styles[prop] = parsedValue;
                });
                return styles;
            }
        }
    }
    
    // 边框宽度解析
    if (['border', 'border-t', 'border-r', 'border-b', 'border-l'].includes(property)) {
        const propertyMap = {
            'border': ['border-width'],
            'border-t': ['border-top-width'],
            'border-r': ['border-right-width'],
            'border-b': ['border-bottom-width'],
            'border-l': ['border-left-width']
        };
        
        const cssProperties = propertyMap[property];
        if (cssProperties) {
            const parsedValue = parseValueWithUnit(value, { platform, h5Unit, remBase });
            if (parsedValue) {
                const styles = {};
                cssProperties.forEach(prop => {
                    styles[prop] = parsedValue;
                });
                return styles;
            }
        }
    }
    
    return null;
} 